import sys
from time import sleep
import pygame
from Bullet import Bullet
from alien import Alien

"""消息循环，接收键盘及鼠标事件"""


def check_event(ship, ai_setting, screen, bullets, play_button, game_state, aliens, score_board):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            print("python exit")
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_event(event, ship, ai_setting, screen, bullets);
        elif event.type == pygame.KEYUP:
            check_keyup_event(event, ship);
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos();
            check_play_button(mouse_x, mouse_y, play_button, game_state, aliens, bullets, ship, ai_setting, screen,  score_board)


# 检测鼠标是否点击了“Play”按钮
def check_play_button(mouse_x, mouse_y, play_button, game_state, aliens, bullets, ship, ai_setting, screen,score_board):
    if play_button.rect.collidepoint(mouse_x, mouse_y) and not game_state.game_active:
        game_state.game_active = True;
        game_state.reset();
      #  pygame.mixer.music.play(-1, 0);
        #pygame.mixer.init();
       # pygame.mixer.music.load("music/plane.mp3");
       # pygame.mixer.music.play(-1, 0);


      #  pygame.mouse.set_visible(False);
        score_board.prep_score();
        score_board.prep_height_score();
        score_board.prep_level()
        score_board.prep_ships();

        aliens.empty();
        bullets.empty();
        ship.center_ship();
        ai_setting.initialize_dynamic_settings();
        create_feet(ai_setting, screen, aliens, ship)


"""按键按下事件"""


def check_keydown_event(event, ship, ai_setting, screen, bullets):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True;
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True;
    elif event.key == pygame.K_UP:
        ship.moving_up = True;
    elif event.key == pygame.K_DOWN:
        ship.moving_down = True;
    elif event.key == pygame.K_q:  # 按键Q退出窗口
        sys.exit()
    elif event.key == pygame.K_SPACE:
        # 发射子弹
        fire_bullet(ship, ai_setting, screen, bullets)


"""按键抬起事件"""


def check_keyup_event(event, ship):
    if (event.key == pygame.K_RIGHT):
        ship.moving_right = False;
    elif (event.key == pygame.K_LEFT):
        ship.moving_left = False;
    elif event.key == pygame.K_UP:
        ship.moving_up = False;
    elif event.key == pygame.K_DOWN:
        ship.moving_down = False;


"""绘制屏幕画面"""


def update_screen(screen, ship, ai_settings, bullets, aliens, start_button, game_state,score_board):
    screen.fill(ai_settings.bg_color)




    score_board.show_score();
    if game_state.game_active:
        for bullet in bullets.sprites():
            bullet.drawBullet()

    ship.draw()
    # for alien in aliens.sprites():
    # alien.drawAlien()
    # 绘制外星人
    aliens.draw(screen);
    if not game_state.game_active:
        start_button.draw_button();
    pygame.display.flip()


# print("python flip")


"""更新子弹位置及数量"""


def update_bullet(bullets, aliens, ai_setting, screen, ship,game_state,score_board):
    # 修改子弹位置
    bullets.update()
    # 删除已消失的子弹
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)

    # 检查子弹和敌人是否碰撞
    check_bullets_aliens_collide(bullets, aliens, ai_setting, screen, ship,game_state,score_board)


def check_height_score(game_state,score_board):
    if game_state.score > game_state.height_score:
        game_state.height_score = game_state.score;
        score_board.prep_height_score()





def check_bullets_aliens_collide(bullets, aliens, ai_setting, screen, ship,game_state,score_board):
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True);
    if collisions:
        for aliens in collisions.values():
            game_state.score += ai_setting.alien_points;
            score_board.prep_score();
            check_height_score(game_state,score_board);
            score_board.prep_height_score();
            pygame.mixer.music.play(1, 0);




    if len(aliens) == 0:
        bullets.empty();
        ai_setting.increase_speed();
        create_feet(ai_setting, screen, aliens, ship)
        ai_setting.alien_points += 10;
        game_state.level += 1;
        score_board.prep_level();


"""发射子弹"""


def fire_bullet(ship, ai_setting, screen, bullets):
    if len(bullets) < ai_setting.bullet_allowed:
        # 创建一颗子弹，加入编组
        new_bullet = Bullet(ai_setting, screen, ship)
        bullets.add(new_bullet)


"""创建一群卫星人"""


def create_feet(ai_setting, screen, aliens, ship):
    alien = Alien(ai_setting, screen);
    alien_width = alien.rect.width;
    ship_height = ship.rect.height;
    alien_nums_x = get_numbers_alien(ai_setting, alien_width);
    rows_num = get_rows_alien(ai_setting, alien.rect.height, ship_height);

    # 多行
    for row_index in range(1):
        # 创建一行外星人
        for alien_index in range(alien_nums_x):
            create_alien(ai_setting, screen, aliens, alien_index, row_index);


def get_numbers_alien(ai_setting, alien_width):
    available_space = ai_setting.screen_width - 2 * alien_width;
    alien_nums_x = (int)(available_space / (2 * alien_width));
    return alien_nums_x;


"""创建1个外星人"""


def create_alien(ai_setting, screen, aliens, alien_index, row_index):
    alien = Alien(ai_setting, screen);
    alien_width = alien.rect.width;
    alien_height = alien.rect.height;
    alien.x = alien_width + 2 * alien_width * alien_index;
    alien.rect.x = alien.x;
    alien.y = alien_height + 2 * alien_height * row_index;
    alien.rect.y = alien.y;
    aliens.add(alien);


# 得到行数
def get_rows_alien(ai_setting, alien_height, ship_height):
    available_y_space = ai_setting.screen_height - 3 * alien_height - ship_height;
    rows = int(available_y_space / (2 * alien_height));
    return rows;


# 更新外星人的位置
def update_alien(aliens, bullets, ship, ai_setting, game_state, screen, score_board):
    check_fleet_edges(ai_setting, aliens)
    aliens.update();

    # 检查外星人是否与飞机碰撞
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hint(aliens, bullets, ship, game_state, ai_setting, screen, score_board)
    # 检查外星人是否触底
    check_alien_bottom(aliens, bullets, ship, game_state, screen, ai_setting, score_board);


def check_alien_bottom(aliens, bullets, ship, game_state, screen, ai_setting, score_board):
    screen_rect = screen.get_rect();
    for alien in aliens:
        if alien.rect.bottom >= screen_rect.bottom:
            ship_hint(aliens, bullets, ship, game_state, ai_setting, screen, score_board)
            break;


def ship_hint(aliens, bullets, ship, game_state, ai_setting, screen,score_board):
    if game_state.ship_left > 0:
        game_state.ship_left -= 1
        score_board.prep_ships();
        if game_state.ship_left == 0:
            game_state.reset();

            game_state.game_active = False;
            pygame.mouse.set_visible(True);
        aliens.empty();
        bullets.empty();
        create_feet(ai_setting, screen, aliens, ship)
        ship.center_ship();
        sleep(0.5);
    else:
        game_state.reset();
        game_state.game_active = False;
        pygame.mouse.set_visible(True);


# 检查外星人是否已到屏幕水平边缘，如果到了整体往下垂直移动，并改变水平移动的方向
def check_fleet_edges(ai_setting, aliens):
    for alien in aliens.sprites():
        if alien.check_edge():
            change_fleet_direction(aliens, ai_setting)
            break;


def change_fleet_direction(aliens, ai_setting):
    for alien in aliens:
        alien.rect.y += ai_setting.feet_drop_factor;
    ai_setting.feet_direction *= -1;
